﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using HollywoodHackers.Storage.Repositories;
using HollywoodHackers.Storage.Models;
using HollywoodHackers.Storage.Queue;

namespace HollywoodHackers.Worker
{
    public class WorkerRole : RoleEntryPoint
    {
        ShoppingCartQueue cartQueue;
        ToastQueue toastQueue;
        UserTextNotificationRepository toastRepository;

        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("WorkerRole1 entry point called", "Information");

            toastRepository = new UserTextNotificationRepository();
            InitQueue();

            while (true)
            {
                Thread.Sleep(10000);
                Trace.WriteLine("Working", "Information");

                ProcessNewTextNotifications();
                ProcessShoppingCarts();
            }
        }

        private void InitQueue()
        {
            cartQueue = new ShoppingCartQueue();
            toastQueue = new ToastQueue();
        }

        private void ProcessNewTextNotifications()
        {
            CloudQueueMessage cqm = toastQueue.GetMessage();

            while (cqm != null)
            {
                ToastQueueMessage message = QueueMessageBase.FromMessage<ToastQueueMessage>(cqm);

                toastRepository.AddNotification(new UserTextNotification()
                {
                    MessageText = message.MessageText,
                    MessageDate = DateTime.Now,
                    TargetUserName = message.TargetUserName,
                    Title = message.Title
                });

                toastQueue.DeleteMessage(cqm);

                cqm = toastQueue.GetMessage();
            }
        }

        private void ProcessShoppingCarts()
        {
            CloudQueueMessage cqm = cartQueue.GetMessage();            

            while (cqm != null)
            {             
                ShoppingCartMessage cart = QueueMessageBase.FromMessage<ShoppingCartMessage>(cqm);

                toastRepository.AddNotification(new UserTextNotification()
                {
                    MessageText = String.Format("Your shopping cart containing {0} items has been processed.", cart.CartItems.Length),
                    MessageDate = DateTime.Now,             
                    TargetUserName = cart.UserName
                });

                cartQueue.DeleteMessage(cqm);

                cqm = cartQueue.GetMessage();
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            DiagnosticMonitor.Start("DiagnosticsConnectionString");

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            RoleEnvironment.Changing += RoleEnvironmentChanging;

            return base.OnStart();
        }

        private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
        {
            // If a configuration setting is changing
            if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
            {
                // Set e.Cancel to true to restart this role instance
                e.Cancel = true;
            }
        }
    }
}
